﻿/// <reference path="../jquery.min.js" />
/// <reference path="rsseasy.v2.js" />
/// <reference path="../app.js" />
/// <reference path="validated.v4.min.js" />


$("[horizontalslip]").horizontalslip();
$("[verticalslip]").verticalslip();
$("[backtotop]").backtotop();
$("[scrolltoel]").scrolltoel();
$("[switchslip]").switchslip();//slideslip
$("[tabswitch]").tabswitch();
$("[loopslip]").loopslip();
$("[underline]").underline();
$("[pageslide]").pageslide();
$("input[readonly]").focus(function () {
    this.blur();
});

//禁止自动填充
$("input:not([autocomplete])").prop("autocomplete", "off");

$(function () {
    //图片验证码、同时获取验证码令牌生成
    $("[ry-imgtoken]").click(function () {
        var t = $(this);
        new Ajax("validate/base64").getJson(function (data) {
            t.attr("src", "data:image/png;base64," + data["base64"]);
            RssApp.ImgToken = data["imgtoken"];
        });
    }).first().click();

    //AJAX
    $("[ry-ajax]").on("rssajax", function () {
        var t = $(this);
        t.data("rssajax").getJson(function (data) {
            $(t.attr("pagingbind")).paging(t);
        });
    }).each(function () {
        var t = $(this), api = t.data("api"), paging = t.data("defalut"), pagesize = t.data("pagesize") || 10;
        var ajax = new Ajax(api).keyvalue("pagesize", pagesize);
        t.data("rssajax", ajax).trigger("rssajax");
    });
});

//选择用户
$("[ry-popupuser]").click(function () {
    var t = $(this);
    RssWin.onwinreceivemsg = function (data) {
        t.val(data["myid"]);
    }
    RssWin.open(t.attr("ry-popupuser") || "/user/select.jsp", 400, 500);
});

//发送短信验证码
$("[ry-smsverify]").each(function () {
    var t = $(this), smscode = count = 60;
    t.click(function () {
        try {
            var dict = new RssDict().keyvalue($("#" + t.attr("ry-smsverify")).serializeArray()).keyvalue({ "imgtoken": RssApp.ImgToken, "matter": t.data("matter") }).getDict(), act = t.data("act") || "verify";
            if (!dict["telphone"]) {
                dict["telphone"] = dict["account"];
            }
            ValidatedV4(dict).isMobphone("telphone").isImgCode("imgcode").isToken("imgtoken");
            if (count != smscode) {
                return;
            }
            --count;
            RssTask.add("smscode", function () {
                t.html(count + "秒重新发送");
                if (count <= 0) {
                    t.html("重新发送");
                    RssTask.remove("smscode");
                    count = smscode;
                    return;
                }
                --count;
            }, 1000).start();

            new Ajax("sms/" + act).keyvalue(dict).setLoading().setRssCode(function (code) {
                RssCode.alert(code);
                count = 0;
            }).getJson(function (json) {
                RssApp.SmsToken = json["smstoken"];
            });
        } catch (ex) {
            RssCode.alert(ex);
        }
    });
});

//短信登陆登陆
$("[ry-smslogin]").click(function () {
    var wrap = $("#" + $(this).attr("ry-smslogin"));
    if (wrap.find("[agreement]").length && !wrap.find("[agreement]:checked").length) {
        RssCode.alert("261");
        return;
    }
    new Ajax("user/sms/login").keyvalue(wrap.serialize()).setLoading().keyvalue("invitemyid", RssUser.Data.invitemyid || "").keyvalue("smstoken", RssApp.SmsToken).getJson(function (json) {
        RssUser.Update(json);
        if (window.RssWeiXin) {
            RssWeiXin.Bind();
        }

        RssUser.onLogin(json);
    });
});

// 账号密码登陆
$("[ry-accountlogin]").click(function () {
    try {
        var wrap = $("#" + $(this).attr("ry-accountlogin"));
        if (wrap.find("[agreement]").length && !wrap.find("[agreement]:checked").length) {
            RssCode.alert("261");
            return;
        }
        var dict = new RssDict().keyvalue(wrap.serialize()).getDict();
        ValidatedV4(dict).isAccount("account").isPwd("pwd").isVerifyCode("imgcode");
        new Ajax("user/login").keyvalue(dict).keyvalue("imgtoken", RssApp.ImgToken).setLoading().postJson(function (json) {
            RssUser.Update(json);
            if (window.RssWeiXin) {
                RssWeiXin.Bind();
            }
            RssUser.onLogin(json);
        });
    } catch (e) {
        RssCode.alert(e);
    }
});

//格式化百分数：格式300(分子),800(分母)
$("[ry-percent]").each(function () {
    var t = $(this), vals = t.attr("ry-percent").split(",");
    t.html((parseFloat(vals[0]) / parseFloat(vals[1]) * 100).toFixed(2) + "%");
});

//账号密码注册
$("[ry-accountreg]").click(function () {
    try {
        var wrap = $("#" + $(this).attr("ry-accountreg"));
        if (wrap.find("[agreement]").length && !wrap.find("[agreement]:checked").length) {
            RssCode.alert("261");
            return;
        }
        var dict = new RssDict().keyvalue(wrap.serialize()).keyvalue("invitemyid", RssUser.Data.invitemyid || "").getDict();
        ValidatedV4(dict).isAccount("account").isPwd("pwd").isVerifyCode("imgcode");
        new Ajax("user/reg").keyvalue(dict).setLoading().keyvalue("imgtoken", RssApp.ImgToken).postJson(function (json) {
            RssUser.Update(json);
            if (window.RssWeiXin) {
                RssWeiXin.Bind();
            }
            RssUser.onLogin(json);
        });
    } catch (e) {
        RssCode.alert(e);
    }
});

$("[ry-timing]").each(function () {
    var t = $(this);
    t.html(Date.time(t.attr("ry-timing")));
});
//短信修改密码
$("[ry-smspwd]").click(function () {
    try {
        var dict = new RssDict().keyvalue($("#" + $(this).attr("ry-smspwd")).serializeArray()).getDict();
        ValidatedV4(dict).isMobphone("telphone").isSmsCode("smscode").isPwd("pwd");
        new Ajax("user/sms/pwd").keyvalue(dict).setLoading().keyvalue("smstoken", RssApp.SmsToken).postJson(function (json) {
            RssUser.onSmsPwd(json);
        });
    } catch (e) {
        RssCode.alert(e);
    }
});

//手机短信验证注册
$("[ry-smsreg]").click(function () {
    try {
        var wrap = $("#" + $(this).attr("ry-smsreg"));
        var dict = new RssDict().keyvalue(wrap.serialize()).getDict();

        ValidatedV4(dict).isMobphone("telphone").isPwd("pwd").isVerifyCode("smscode");
        if (dict["repwd"] && dict["repwd"] != dict["pwd"]) {
            throw "107";
        }
        new Ajax("user/sms/reg").keyvalue(dict).setLoading().keyvalue("smstoken", RssApp.SmsToken).postJson(function (json) {
            RssUser.Update(json);
            if (window.RssWeiXin) {
                RssWeiXin.Bind();
            }
            RssUser.onSmsReg(json);
        });
    } catch (e) {
        RssCode.alert(e);
    }
});

//管理员登陆
$("[ry-adminlogin]").click(function () {
    try {
        var wrap = $("#" + $(this).attr("ry-adminlogin"));
        var dict = new RssDict().keyvalue(wrap.serialize()).getDict();
        ValidatedV4(dict).isAccount("account").isPwd("pwd").isVerifyCode("imgcode");
        new Ajax("staff/login").keyvalue(dict).setLoading().keyvalue("imgtoken", RssApp.ImgToken).postJson(function (json) {
            RssUser.Update(json);
            $.each(json, function (key, val) {
                Cookie.Set(key, val);
            });
            Cookie.Set("staffmyid", json["myid"]);
            RssUser.onLogin(json);
        });
    } catch (e) {
        RssCode.alert(e);
    }
});

$("[ry-for]").each(function () {
    var t = $(this), vals = t.attr("ry-for").split(','), dict = [];
    var start = parseFloat(vals[0]), end = parseFloat(eval('(' + vals[1] + ')')), step = parseFloat(vals[2]) || 1;
    for (var i = start; i < end; i += step) {
        dict.push({ "key": i, "value": i })
    }
    t.maplist(dict);
});

//允许输入
$("[ry-allow]").each(function () {
    var t = $(this);
    t.keydown(function (e) {
        return e.which == 8 || e.which == 9 || e.which == 13 || e.which == 46 || (e.which > 36 && e.which < 41) || allowinput[t.attr("ry-allow")](e);
    });
})
//点击事件扩展
$("[ry-click]").click(function (e) {
    e.preventDefault();
    var t = $(this);
    RssClick.factory(t, t.attr("ry-click"));
});

//打开包含的图片
$("[ry-imgopen]").each(function () {
    var t = $(this), open = t.find(t.attr("ry-imgopen"));
    open.click(function () {
        window.open($(this).attr("src"));
    });
});

$("[ry-link]").click(function () {
    var link = $(this).attr("ry-link");
    if (link) {
        location.href = link;
        return;
    }
    history.back();
});
$("[ry-hisback]").click(function (ev) {
    ev.stopPropagation();
    ev.preventDefault();
    history.back();
});
$("[ry-ifrback]").click(function (ev) {
    ev.stopPropagation();
    ev.preventDefault();
    var id = $(this).attr("ry-ifrback") || "workspace", ifr = parent.window.frames[id || 0], win = ifr.contentWindow || ifr.window;
    win.history.back();
});
$(".hisback").click(function (ev) {
    ev.preventDefault();
    ev.stopPropagation();
    JsAdapter.onRollBack();
});
$("[selectall]").click(function () {
    var t = $(this), sel = $(t.attr("selectall"));
    sel.prop("checked", this.checked);
});

$("[disedit]").each(function () {
    var t = $(this);
    if (t.val()) {
        t.prop("disabled", true);
    }
});


//下载文件
$(document).on("click", "[downfile]", function () {
    RssDownFile.Start($(this).attr("downfile"));
});

//通过自定义属性JS生成二维码,ry-qrcode属性指定生成的内容,render属性为渲染容器：取值img|canvas(默认);
$('[ry-qrcode]').each(function () {
    var t = $(this);
    t.qrcode({ "text": t.attr("ry-qrcode"), "render": t.data("render") });
});

//删除图片列表中的图片
$(".photolist").on("click", ".btndel", function () {
    var p = $(this).parent();
    p.parent().children().last().show();
    p.remove();
});
//登陆背景图片
$("[ry-loginbg]").each(function () {
    var t = $(this), img = t.find(">img");
    t.append('<img src="' + img.attr("src").replace("/small", "") + '" />');
});
$("[ry-loginout]").click(function () {
    Cookie.RemoveAll();
    RssUser.LoginOut();
    location.href = $(this).attr("ry-loginout");
});
//上传文件
$("[ry-upload]").each(function () {
    var t = $(this), method = t.attr("ry-upload"), name = t.data("name") || "picture", amount = parseInt(t.data("amount")) || 1;

    function onComplete(json) {
        if (amount > 1) {
            var html = $('<li class="uploadpreview"><b class="btndel"></b><div><img src="' + (json["base64"] ? json["base64"] : RssUpFile.DoMain + json["url"]) + '" /><input type="hidden" name="' + name + '" value="' + json["url"] + '" /><input type="hidden" value="' + json["filesize"] + '" /></div></li>');
            html.insertBefore(t);
            if (t.parent().children().length > amount) {
                t.hide();
            }
        } else {
            t.find("div").html('<img src="' + (json["base64"] ? json["base64"] : RssUpFile.DoMain + json["url"]) + '" /><input type="hidden" name="' + name + '" value="' + json["url"] + '" />');
        }
        console.log(t.html());
        RssWin.MaskLayer.close();
        RssWin.LoadBox.close();
    }

    RssUpFile.onStart = function () {
        RssWin.MaskLayer.show();
        RssWin.LoadBox.show();
    }

    switch (method) {
        case "input":
            t.find("[type='file']").change(function () {
                if (!this.files.length) {
                    return;
                }

                RssUpFile.onComplete = onComplete;

                new Ajax().setUrl(RssUpFile.ApiHost).setLoading().keyform("upfile", this.files[0]).sendFrom(function (json) {
                    RssUpFile.onComplete(json)
                });

            }).click(function (ev) {
                ev.stopPropagation();
            });
            break;
        case "popup":
            t.click(function () {
                RssPopup.SetTitle("选择图片").AddHtml('<li data-action="gallery">相册</li><li data-action="takephoto">拍照</li>').ItemWrap.find("li").unbind().click(function () {
                    var params = { "action": $(this).data("action") };
                    if (t.data("cut")) {
                        params["cut"] = parseInt(t.data("cut")) || 300;
                    }
                    RssUpFile.onComplete = onComplete;
                    RssUpFile.Submit(params);
                });
                RssPopup.Popup();
            });
            break;
    }
});

//图片剪切/上传
$("[ry-cropper]").each(function () {
    var t = $(this);

    t.cropper({ "src": t.attr("ry-cropper"), "canvas": t.data("canvas"), "preview": t.data("preview") || "", "viewMode": t.data("viewmode") || 1, "autoCropArea": t.data("croparea") || 0.6 }).click(function () {
        var baseurl = t.data("cropper").getCroppedCanvas().toDataURL();
        if (t.data("upfile") != undefined) {
            RssWin.MaskLayer.show();
            RssWin.LoadBox.show();
            new Ajax().setUrl(RssUpFile.ApiHost + "/base64").keyvalue("base64", baseurl).keyvalue(t.data("upfile").toKeyValue()).postJson(function (json) {
                RssWin.MaskLayer.close();
                RssWin.LoadBox.close();
                RssUpFile.onComplete(json);
            });
        }

        $("[name='" + t.data("datawrap") + "']").val(baseurl);
    });
});
//在线编辑器
$("[ry-editor]").each(function () {
    UE.getEditor(this.id, eval("({" + $(this).attr("ry-editor") + "})"));
});


//IP数字换IP
$("[ry-ip]").each(function () {
    var t = $(this);
    var hex = parseInt(t.attr("ry-ip")).toString("16").padleft(8, '0');
    var vals = hex.match(/\w{2}/img);
    t.html(parseInt(vals[0], 16) + "." + parseInt(vals[1], 16) + "." + parseInt(vals[2], 16) + "." + parseInt(vals[3], 16));
});

//金额格式表示
$("[ry-money]").each(function () {
    var t = $(this);
    var money = t.attr("ry-money").split(",");
    t.html(money[0].tomoney(money[1], parseInt(money[2])));
});

//17位身份证增加X
$("[ry-idcard]").each(function () {
    var t = $(this);
    var idcard = t.attr("ry-idcard");
    if (idcard.length == 17) {
        idcard += "X"
    }
    switch (this.tagName.toLowerCase()) {
        case "input":
            t.val(idcard);
            break;
        default:
            t.html(idcard);
            break;
    }
});

//电话号码转换
$("[ry-phone]").each(function () {
    var t = $(this);
    var fixedphone = t.attr("ry-phone");
    if (fixedphone.length < 8) {
        return;
    }
    var quhao = /^(10|2[\d]|[\d]{3})/g;
    var phone = fixedphone.match(quhao);
    switch (this.tagName.toLowerCase()) {
        case "input":
            break;
        default:
            t.html(fixedphone.replace(quhao, function (val) {
                return "0" + val + "-";
            }));
            break;
    }
});

//时间戳换日期格式
$("[ry-date]").each(function () {
    var t = $(this);
    var data = t.attr("ry-date").split(",");
    if (!data[0]) {
        return;
    }
    var ft = data[1] || "yyyy-MM-dd HH:mm:ss";
    var val = new Date(parseInt(eval(data[0])) * 1000).toString(ft);
    switch (this.tagName.toLowerCase()) {
        case "input":
            t.val(val);
            break;
        default:
            t.html(val);
            break;
    }
});

//全选、取消全选
$('[ry-selectall]').click(function () {
    $($(this).attr("ry-selectall")).prop("checked", this.checked);
});

$("[ry-lang]").each(function () {
    var t = $(this), key = t.attr("ry-lang");
    switch (t.get(0).tagName.toLowerCase()) {
        case "input":
        case "textarea":
            break;
        default:
            t.html(RssLang.dict[key] || "");
            break;
    }
});

//订单取消
$('[ry-ordercancel]').click(function () {
    RssOrder.Cancel($(this).attr("ry-ordercancel"));
});

$('[ry-detailcancel]').click(function () {
    RssOrderDetails.Cancel($(this).attr("ry-detailcancel"));
});

//获取汉字拼音
$("[ry-spelling]").keyup(function () {
    var t = $(this), val = t.val(), wrap = $("#" + t.attr("ry-spelling"));
    if (wrap.length) {
        wrap.val(val.getpinyin(parseInt(t.data("capitalize"))));
    }
});

//预览
$("[ry-preview]").click(function (ev) {
    ev.preventDefault();
    var t = $(this);
    window.open(RssApp.WwwHost + t.attr("href"));
});

$("[ry-excel]").click(function () {
    var url = "excel/" + $(this).attr("ry-excel");
    if (location.search.length) {
        url += (url.indexOf("?") == -1 ? "?" : "&") + location.search.substring(1);
    }
    window.open(url);
});

//图片按需加载
$(function () {
    $(document).on("scroll.lazyload", function () {
        var viewh = $(window).height();
        var lazyload = $("[ry-lazyload]");
        if (!lazyload.length) {
            $(this).off("scroll.lazyload");
        }
        var vtop = $(this).scrollTop() + viewh;
        lazyload.each(function () {
            var t = $(this);
            var offsetTop = t.offset().top;
            if (offsetTop <= vtop) {
                var img = new Image();
                img.onload = function () {
                    t.attr("src", img.src);
                    img = null;
                }
                img.src = RssUpFile.DoMain + t.attr("ry-lazyload");
                t.removeAttr("ry-lazyload");
            }
        });
    }).trigger("scroll.lazyload");
});

//rydata.js加载完毕后
RssDict.onload = function () {
    //数据自动绑定
    $.each(window.rydata || {}, function (k, v) {
        $("[" + k + "]").each(function () {
            var t = $(this), dict = rydata[k] || {}, keys = t.attr(k).split(","), vals = [], join = t.data("join") || "";
            $.each(keys, function (idx, val) {
                val = dict[val] || val;
                if ($.isArray(val)) {
                    val = val[0];
                } else if ($.isFunction(val)) {
                    val = val();
                }
                vals.push(val);
            });
            switch (this.tagName.toLowerCase()) {
                case "select":
                    t.val(keys[0]);
                    break;
                case "input":
                case "textarea":
                    t.val(vals.join(join));
                    break;
                default:
                    t.html(vals.join(join));
                    break;
            }
        });
    });

    $("[ry-links]").each(function () {
        var t = $(this), links = t.attr("ry-links").split(","), html = "";
        $.each(links, function (idx, url) {
            html += '<a href="' + RssUpFile.DoMain + url + '" target="_blank">' + url + '</a>';
        });
        t.html(html);
    });

    $("[ry-selectitem]").each(function () {
        var t = $(this), dict = rydata[t.attr("ry-selectitem")] || {};
        t.mapmodalitem(dict);
    });

    //映射数组格式键值对列表数据
    $("[ry-maplist]").each(function () {
        var t = $(this);
        t.maplist(rydata[t.attr("ry-maplist")] || []);
    });
    //映射键值对对象数据
    $("[ry-mapjson]").each(function () {
        var t = $(this);
        t.mapjson(rydata[t.attr("ry-mapjson")] || []);
    });

    //级联
    $("[ry-cascade]").cascade();

    //下拉选择框
    $("[ry-select]").each(function () {
        var t = $(this), dict = rydata[t.attr("ry-select")] || {}, html = "";

        $.each(dict, function (k, v) {
            if (v.constructor == Array) {
                v = v[0];
            }
            html += '<option value="' + k + '">' + v + '</option>';
        });
        if (this.tagName.toLowerCase() != "select") {
            t = t.append('<select></select>');
        }
        t.append(html);
        if (t.data("val")) {
            t.val(t.data("val"));
        }
    });
    //单选
    $("[ry-radio]").each(function () {
        createinput($(this), "radio");
    });
    //多选
    $("[ry-checkbox]").each(function () {
        createinput($(this), "checkbox");
    });
    function createinput(t, tp) {
        var key = t.attr("ry-" + tp), dict = window.rydata[key] || {}, html = "", name = t.data("name") || key, id = t.data("id") || name, keys = (t.data("key") || "");
        if (keys.length) {
            keys = keys.split(',');
            var tmp = {};
            $.each(keys, function (k, v) {
                if (dict[v]) {
                    tmp[v] = dict[v];
                }
            });
            dict = tmp;
        }
        $.each(dict, function (k, v) {
            html += '<label><input type="' + tp + '" id="' + id + k + '" name="' + name + '" value="' + k + '" />' + (v.constructor == Array ? v[0] : v) + '</label>';
        });
        t.html(html);
        var item = t.find("input[name=" + name + "]");
        if (t.data("val")) {
            item.val(t.data("val").toString().split(","));
        }
        if (tp == "checkbox") {
            item.removeAttr("name");
            var ipt = $('<input type="hidden" name="' + name + '" value="' + (t.data("val") || "") + '"/>');
            t.append(ipt);
            item.click(function () {
                var val = [];
                t.find("input:checked").each(function () {
                    val.push(this.value);
                });
                ipt.val(val.join());
            })
        }
    }

    $(function () {
        var dict = {}, idx = -1, val = 0, name = "", id = "", valkey = false, deploy = "", showoffset = false, inherit = -1;

        function powerlist(parentid, tp) {
            var data = Object.Query(dict, [1, parentid]);
            if (Object.Count(data)) {
                var html = "";
                $.each(data, function (k, v) {
                    val = idx > -1 ? v[idx] : k;
                    if (v[inherit] && !RssPower.verify(v[inherit])) {
                        return;
                    }
                    html += '<li class="line options" ' + deploy + '><input type="' + tp + '" id=' + id + k + ' name="' + name + '" value="' + (valkey ? k : val) + '" pid="' + id + v[1] + '"/><label for=' + id + k + '>' + v[0] + (showoffset ? "(" + v[showoffset] + ")" : "") + '</label></li>';
                    if (parseInt(k)) {
                        html += '<li class="options' + deploy + '"><ul>' + powerlist(k, tp) + "</ul></li>";
                    }
                });
                return html;
            }
            return "";
        }
        $("[ry-options]").each(function () {
            var t = $(this), tp = t.data("input") || "radio", rel = t.data("check") === undefined;
            inherit = t.data("inherit");
            showoffset = t.data("offset") || false;
            deploy = t.data("deploy") != null ? " deploy" : "";
            name = t.data("name") || "pid";
            idx = t.data("idx") || -1;
            valkey = t.data("usekey");
            id = name.replace("[]", "");

            dict = rydata[t.attr("ry-options")] || {};
            t.html(powerlist(0, tp)).find("input").click(function (ev) {
                RssEvent.onLevelClick(this, ev);
            });
            if (deploy) {
                t.find('[' + deploy + '] label').click(function () {
                    $(this).parent().next().toggleClass("deploy");
                });
            }
            t.trigger("ryoptions");
            var tag = t.find("[name='" + name + "']");
            if (t.data("val")) {
                tag.val(t.data("val").toString().split(","));
            }
            if (rel) {
                if (tp == "checkbox") {
                    tag.click(function () {
                        clickup(tag, this);
                        clickdown(tag, this);
                    });
                }
            }

            var power = t.data("options");
            if (power) {
                var len = power.length;
                for (var i = 0; i < len; i++) {
                    if (power.substr(i, 1) === "1") {
                        $("[name='" + name + "'][value='" + (i + 1) + "']").prop("checked", true);
                    }
                }
            }

            var mypower = t.data("myoptions");
            if (mypower) {
                var len = mypower.length;
                for (var i = 0; i < len; i++) {
                    if (mypower.substr(i, 1) === "0") {
                        $("[name='" + name + "'][value='" + (i + 1) + "']").prop("disabled", true).parent().hide();
                    }
                }
            }
        });
        function clickup(tag, t) {
            var pid = $(t).attr("pid");
            var tmp = $("#" + pid);
            tmp.prop("checked", tag.filter("[pid=" + pid + "]:checked").length);
            tmp.each(function () {
                clickup(tag, this);
            });
        }
        function clickdown(tag, t) {
            var tmp = tag.filter("[pid=" + t.id + "]");
            tmp.prop("checked", t.checked);
            tmp.each(function () {
                clickdown(tag, this);
            });
        }
    });

    $(".modalselect select").change(function () {
        var t = $(this), val = $(t.attr("map-val"));
        val.val(t.find("option:selected").text());
    }).change();
}